package com.tlkj.common.curd.service.impl;

import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.Page;
import com.tlkj.common.curd.entity.ApiMenu;
import com.tlkj.common.curd.mapper.ApiMapper;
import com.tlkj.common.curd.mapper.ApiMenuMapper;
import com.tlkj.common.curd.service.ApiMenuService;
import com.tlkj.common.curd.vo.MenuTree;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * API目录 - ServiceImpl
 * @author flyong86
 * @since 2024年6月19日
 */
@RequiredArgsConstructor
@Service
public class ApiMenuServiceImpl implements ApiMenuService {

    private final ApiMenuMapper apiMenuMapper;
    private final ApiMapper apiMapper;

    @Override
    public ApiMenu queryById(String id) {
        return apiMenuMapper.queryById(id);
    }

    @Override
    public Page<ApiMenu> paginQuery(ApiMenu apiMenu, Page<ApiMenu> page) {
        return null;
    }

    @Override
    public ApiMenu insert(ApiMenu apiMenu) {
        apiMenu.setId(IdUtil.getSnowflakeNextId() + "");
        apiMenuMapper.insert(apiMenu);
        return apiMenu;
    }

    @Override
    public ApiMenu update(ApiMenu apiMenu) {
        apiMenuMapper.update(apiMenu);
        return apiMenu;
    }

    @Override
    public boolean deleteById(String id) throws Exception {

        if (apiMapper.countByMenuId(id) > 0) {
            throw new Exception("该目录下存在API,无法删除!");
        }
        apiMenuMapper.deleteById(id);
        return true;
    }

    @Override
    public List<MenuTree> getTrees() {
        List<ApiMenu> list = apiMenuMapper.listAll();

        List<MenuTree> menuTrees = new ArrayList<>();

        // Initialize the map
        for (ApiMenu apiMenu : list) {
            MenuTree menuTree = new MenuTree();
            menuTree.setId(apiMenu.getId());
            menuTree.setName(apiMenu.getName());
            menuTree.setParentId(apiMenu.getParentId());
            menuTree.setChildren(new ArrayList<>());

            menuTrees.add(menuTree);
        }

        // Create a list for roots
        List<MenuTree> roots = new ArrayList<>();

        // Build the tree structure
        for (MenuTree menuTree : menuTrees) {
            if (menuTree.getParentId() == null) {
                buildTree(menuTrees, menuTree);
                // This is a root node
                roots.add(menuTree);
            }
        }

        return roots;
    }

    private void buildTree(List<MenuTree> list, MenuTree parent) {
        for (MenuTree item : list) {
            if (item.getParentId() != null && item.getParentId().equals(parent.getId())) {
                parent.getChildren().add(item);

                buildTree(list, item);
            }
        }
    }
}
